<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="社团" prop="clubName">
            <el-input
               v-model="queryParams.clubName"
               placeholder="请输入社团名称"
               clearable
               style="width: 150px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="标题" prop="title">
            <el-input
               v-model="queryParams.title"
               placeholder="请输入帖子标题"
               clearable
               style="width: 150px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="作者" prop="authorName">
            <el-input
               v-model="queryParams.authorName"
               placeholder="请输入作者姓名"
               clearable
               style="width: 120px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="帖子状态" clearable style="width: 120px">
               <el-option
                  v-for="dict in post_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:post:add']"
            >发帖</el-button>
         </el-col>
         <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="View"
               @click="handleView"
               :disabled="single"
               v-hasPermi="['system:post:query']"
            >查看</el-button>
         </el-col> -->
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >编辑</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="ID" align="center" prop="id" width="80" />
         <el-table-column label="社团" align="center" prop="clubName" width="120" />
         <el-table-column label="标题" align="center" prop="title" min-width="200" show-overflow-tooltip />
         <el-table-column label="作者" align="center" prop="authorName" width="100" />
         <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
               <dict-tag :options="post_status" :value="String(scope.row.status)" />
            </template>
         </el-table-column>
         <el-table-column label="浏览量" align="center" prop="viewCount" width="80" />
         <el-table-column label="评论数" align="center" prop="commentCount" width="80" />
         <el-table-column label="点赞数" align="center" prop="likeCount" width="80" />
         <el-table-column label="发布时间" align="center" prop="createdAt" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['system:post:query']">查看</el-button>
               <el-button link type="primary" icon="ChatDotRound" @click="handleComment(scope.row)" v-hasPermi="['system:post:comment']">评论</el-button>
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:post:edit']">编辑</el-button>
               <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:post:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />

      <!-- 发帖对话框 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
         <el-form ref="postRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="选择社团" prop="clubName">
               <el-select v-model="form.clubId" placeholder="请选择社团" style="width: 100%" @change="handleClubChange">
                  <el-option
                     v-for="club in userClubs"
                     :key="club.clubName"
                     :label="club.clubName"
                     :value="club.clubId"
                  />
               </el-select>
            </el-form-item>
            <el-form-item label="帖子标题" prop="title">
               <el-input v-model="form.title" placeholder="请输入帖子标题" />
            </el-form-item>
            <el-form-item label="帖子内容" prop="content">
               <el-input 
                  v-model="form.content" 
                  type="textarea" 
                  placeholder="请输入帖子内容" 
                  :rows="8"
                  show-word-limit
                  maxlength="2000"
               />
            </el-form-item>
            <!-- <el-form-item label="帖子类型" prop="type">
               <el-radio-group v-model="form.type">
                  <el-radio :label="1">普通帖子</el-radio>
                  <el-radio :label="2">公告</el-radio>
                  <el-radio :label="3">活动</el-radio>
               </el-radio-group>
            </el-form-item> -->
            <el-form-item label="是否置顶" prop="isTop">
               <el-switch v-model="form.isTop" />
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">发布</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 帖子详情对话框 -->
      <el-dialog title="帖子详情" v-model="viewOpen" width="900px" append-to-body>
         <div v-if="selectedPost" class="post-detail">
            <!-- 帖子内容 -->
            <div class="post-header">
               <h2>{{ selectedPost.title }}</h2>
               <div class="post-meta">
                  <span>作者：{{ selectedPost.authorName }}</span>
                  <span>社团：{{ selectedPost.clubName }}</span>
                  <span>发布时间：{{ parseTime(selectedPost.createdAt) }}</span>
                  <span>浏览量：{{ selectedPost.viewCount }}</span>
                  <!-- <span>评论数：{{ selectedPost.commentCount }}</span> -->
                  <span>点赞数：{{ selectedPost.likeCount }}</span>
                  
               </div>

            </div>
            
            <div class="post-content">
               <p>{{ selectedPost.content }}</p>
               
            </div>
            <div class="comment-actions">
               <el-button link type="primary" size="small" @click="likePost(selectedPost.id)">
                  <el-icon><Star /></el-icon>
                  点赞 ({{ selectedPost.likeCount }})
               </el-button>
            </div>
            
            <!-- 评论区 -->
            <div class="comment-section">
               <h3>评论区</h3>
               <!-- 发表评论 -->
               <div class="comment-form">
                  <el-input
                     v-model="commentForm.content"
                     type="textarea"
                     placeholder="写下你的评论..."
                     :rows="3"
                     maxlength="500"
                     show-word-limit
                  />
                  <el-button type="primary" @click="submitComment" style="margin-top: 10px;">发表评论</el-button>
               </div>
               
               <!-- 评论列表 -->
               <div class="comment-list">
                  <div v-for="comment in commentList" :key="comment.id" class="comment-item">
                     <div class="comment-header">
                        <span class="comment-author">{{ comment.authorName }}</span>
                        <span class="comment-time">{{ parseTime(comment.createdAt) }}</span>
                     </div>
                     <div class="comment-content">
                        {{ comment.content }}
                     </div>
                     <div class="comment-actions">
                        <el-button link type="primary" size="small" @click="likeComment(comment.id)">
                           <el-icon><Star /></el-icon>
                           点赞 ({{ comment.likeCount }})
                        </el-button>
                        <el-button link type="primary" size="small" @click="replyComment(comment)">
                           回复
                        </el-button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </el-dialog>
   </div>
</template>

<script setup name="Post">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { Star, ChatDotRound } from '@element-plus/icons-vue'
import { listPost, getPost, addPost, updatePost, delPost, listUserClubs, listComments, addComment, likeComment as likeCommentApi,  likePost as likePostApi} from "@/api/system/post";
const { proxy } = getCurrentInstance();
const { post_status } = proxy.useDict("post_status");

const postList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedPost = ref(null);
const commentList = ref([]);
const userClubs = ref([]);

const data = reactive({
  form: {
    id: undefined,
    clubId: undefined,
    title: undefined,
    content: undefined,
    type: 1,
    isTop: false
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clubName: undefined,
    title: undefined,
    authorName: undefined,
    status: undefined
  },
  rules: {
    clubId: [
      { required: true, message: "请选择社团", trigger: "change" }
    ],
    title: [
      { required: true, message: "帖子标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "帖子内容不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "请选择帖子类型", trigger: "change" }
    ]
  },
  commentForm: {
    content: "",
    postId: null,
    parentId: null
  }
});

const { queryParams, form, rules, commentForm } = toRefs(data);

/** 查询帖子列表 */
function getList() {
  loading.value = true;
  listPost(queryParams.value).then(response => {
    postList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取帖子列表失败:', error);
    loading.value = false;
  });
}

/** 获取用户可发帖的社团列表 */
function getUserClubs() {
  listUserClubs().then(response => {
    userClubs.value = response.data || [];
  }).catch(error => {
    console.error('获取用户社团列表失败:', error);
    userClubs.value = [];
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    clubId: undefined,
    title: undefined,
    content: undefined,
    type: 1,
    isTop: false
  };
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getUserClubs();
  open.value = true;
  title.value = "发布新帖子";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getUserClubs();
  const id = row.id || ids.value;
  getPost(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "编辑帖子";
  }).catch(error => {
    console.error('获取帖子详情失败:', error);
    proxy.$modal.msgError("获取帖子详情失败");
  });
}

/** 查看按钮操作 */
function handleView(row) {
  const id = row.id || ids.value;
  getPost(id).then(response => {
    selectedPost.value = response.data || {};
    commentForm.value.postId = id;
    viewOpen.value = true;
    getCommentList(id);
  }).catch(error => {
    console.error('获取帖子详情失败:', error);
    proxy.$modal.msgError("获取帖子详情失败");
  });
}

/** 评论按钮操作 */
function handleComment(row) {
  handleView(row);
}

/** 获取评论列表 */
function getCommentList(postId) {
  listComments({ postId: postId }).then(response => {
    commentList.value = response.rows || [];
  }).catch(error => {
    console.error('获取评论列表失败:', error);
    commentList.value = [];
  });
}

/** 提交评论 */
function submitComment() {
  if (!commentForm.value.content.trim()) {
    proxy.$modal.msgError("请输入评论内容");
    return;
  }
  
  addComment(commentForm.value).then(response => {
    proxy.$modal.msgSuccess("评论发表成功");
    commentForm.value.content = "";
    getCommentList(commentForm.value.postId);
  }).catch(error => {
    proxy.$modal.msgError("评论发表失败：" + (error.message || '未知错误'));
  });
}

/** 点赞评论 */
function likeComment(commentId) {
  likeCommentApi(commentId).then(response => {
    proxy.$modal.msgSuccess("点赞成功");
    getCommentList(commentForm.value.postId);
  }).catch(error => {
    proxy.$modal.msgError("点赞失败：" + (error.message || '未知错误'));
  });
}

/** 点赞帖子 */
function likePost(id) {
  likePostApi(id).then(response => {
    proxy.$modal.msgSuccess("点赞成功");
  getPost(id).then(response => {
    selectedPost.value = response.data || {};
    commentForm.value.postId = id;
    viewOpen.value = true;
    getCommentList(id);
  }).catch(error => {
    console.error('获取帖子详情失败:', error);
    proxy.$modal.msgError("获取帖子详情失败");
  });
  }).catch(error => {
    proxy.$modal.msgError("点赞失败：" + (error.message || '未知错误'));
  });
}

/** 回复评论 */
function replyComment(comment) {
  commentForm.value.content = `@${comment.authorName} `;
  commentForm.value.parentId = comment.id;
}

/** 社团选择变化 */
function handleClubChange(clubId) {
  // 可以在这里添加社团相关的逻辑
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePost(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          proxy.$modal.msgError("修改失败：" + (error.message || '未知错误'));
        });
      } else {
        addPost(form.value).then(response => {
          proxy.$modal.msgSuccess("发布成功");
          open.value = false;
          getList();
        }).catch(error => {
          proxy.$modal.msgError("发布失败：" + (error.message || '未知错误'));
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除帖子ID为"' + postIds + '"的数据项？').then(function() {
    return delPost(postIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);
}

getList();
</script>

<style scoped>
.post-detail {
   padding: 20px 0;
}

.post-header {
   border-bottom: 1px solid #eee;
   padding-bottom: 15px;
   margin-bottom: 20px;
}

.post-header h2 {
   margin: 0 0 10px 0;
   color: #333;
}

.post-meta {
   color: #666;
   font-size: 14px;
}

.post-meta span {
   margin-right: 15px;
}

.post-content {
   margin-bottom: 30px;
   line-height: 1.6;
}

.comment-section {
   border-top: 1px solid #eee;
   padding-top: 20px;
}

.comment-section h3 {
   margin-bottom: 15px;
   color: #333;
}

.comment-form {
   margin-bottom: 20px;
}

.comment-list {
   max-height: 400px;
   overflow-y: auto;
}

.comment-item {
   border-bottom: 1px solid #f5f5f5;
   padding: 15px 0;
}

.comment-header {
   margin-bottom: 8px;
}

.comment-author {
   font-weight: bold;
   color: #333;
   margin-right: 10px;
}

.comment-time {
   color: #999;
   font-size: 12px;
}

.comment-content {
   margin-bottom: 8px;
   line-height: 1.5;
}

.comment-actions {
   display: flex;
   gap: 15px;
}
</style>
